package com.example.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class ProductController {
    @Autowired
    private ProductService service;
    @Value("${server.port}")
    private String serverPort;

    @GetMapping("product/{proId}")
    public String getPro(@PathVariable("proId") Integer proId){
        return serverPort+"正在查询商品:"+service.getById(proId);
    }
    @GetMapping("product/getAll")
    @SentinelResource(value = "getAllProHotKey",blockHandler = "deal_getAllHotKey",fallback = "fallback_getallpro")
    public String getAllPro(@RequestParam(value = "key",required = false) String key){
        //int a=10/0;
        return serverPort+"正在查询所有商品:"+service.getAll();
    }
    @GetMapping("product/getPorPrice/{proId}")
    public Map getProPrice(@PathVariable("proId") Integer proId){
        Map<String,Object> price= new HashMap<>();
        price.put("proPrice",service.getProPriceById(proId));
        return price;
    }

    public String deal_getAllHotKey(String key,BlockException blockException){
        return "兜底方法降级处理，每秒访问次数超过ops阈值时调用";
    }
    public String fallback_getallpro(String key){
        return "代码异常时调用这个方法";
    }
}
